import { ajax } from '../../ajax';
Page({
  data: {
    // 自定义开始时间
    startTime:'',
    // 自定义结束时间
    endTime:'',
    selected: 1,
    // 默认不选
    selStatus: 0,
    // 获取门店列表
    storeList: null,
    // 选择门店状态
    storeStatus:'',
    // 商店编号
    storeNum:'',
    // 时间段标号
    num: 0,
    store_name:'全部门店',
    alipayInAmount: 0,
    alipayInNum: 0,
    alipayOutAmount: 0,
    alipayOutNum: 0,
    alipayRealityAmount: 0,
    total: 0,
    totalNum: 0,
    weixinInAmount: 0,
    weixinInNum: 0,
    weixinOutAmount: 0,
    weixinOutNum: 0,
    weixinRealityAmount: 0
  },
  // 选择时间或商铺
  timeOrStore(e) {
    this.setData({selStatus: e.currentTarget.dataset.type})
    
  },
  // 选择哪个商铺
  selStores(e) {
    console.log(e);
    this.setData({
      storeStatus: e.currentTarget.dataset.index,
      storeNum: e.currentTarget.dataset.storeNum,
      store_name: e.currentTarget.dataset.store_name
    })
    this.getCashierSum({devices:this.data.storeNum,num:this.data.num})
  },
  // 选择今天、昨天、本周
  pickDate(e) {
    this.setData({selected: e.currentTarget.dataset.selectDate})
    let num = e.currentTarget.dataset.selectDate - 1;
    this.setData({num:num})
    if(num === 3){
      console.log('自定义。。。。。')
    }else{
      this.setData({startTime:'',endTime:''})
      this.getCashierSum({devices:this.data.storeNum,num})
    }
    console.log(e.currentTarget.dataset.selectDate)
  },
  // 确定查询门店
  // markSure() {
  //   console.log('确定')
  //   console.log(this.data.storeNum)
  //   if(this.data.storeNum){
  //     this.getCashierSum({devices:this.data.storeNum,num:this.data.num})
  //   }else{
  //     my.showToast({
  //       content:'请先选择门店'
  //     })
  //   }
    
  // },
  // 请求金额数据
  async getCashierSum(item) {
    console.log('system',item.devices)
    console.log('data',item.num)
    let token = my.getStorageSync({ key: 'token' }).data;
    let devices = item.devices? item.devices : my.getStorageSync({ key: 'system' }).data;
    console.log("devices",devices)
    let paramsSum = {
      token,
      devices,
      time_type: typeof item.num === 'undefined'? "" : item.num, 
      start_time: this.data.startTime ? this.data.startTime : '',
      end_time: this.data.endTime ? this.data.endTime : ''
    };
    console.log("paramsSum",paramsSum)
    my.showLoading({content: '加载中...'});
    let sumData = await ajax('/SmallAppSmilePayList', paramsSum)
   
    if(sumData.status === 200) {
       my.hideLoading();
      console.log('2000',sumData.data.data)
      this.setData({
        alipayInAmount: sumData.data.data.alipayInAmount,
        alipayInNum: sumData.data.data.alipayInNum,
        alipayOutAmount: sumData.data.data.alipayOutAmount,
        alipayOutNum: sumData.data.data.alipayOutNum,
        alipayRealityAmount: sumData.data.data.alipayRealityAmount,
        total: sumData.data.data.total,
        totalNum: sumData.data.data.totalNum,
        weixinInAmount: sumData.data.data.weixinInAmount,
        weixinInNum: sumData.data.data.weixinInNum,
        weixinOutAmount: sumData.data.data.weixinOutAmount,
        weixinOutNum: sumData.data.data.weixinOutNum,
        weixinRealityAmount: sumData.data.data.weixinRealityAmount
      })
      this.hidden();
    }
    my.hideLoading();
    console.log(sumData)
  },
  // 阴影部分点击隐藏遮罩层
  hidden() {
    this.setData({selStatus: 0 })
  },
  // 自定义选择时间
  datePickerYMDHMS(e) {
    let that = this;
    if(that.data.selected == 4) {
      console.log(e)
      let statusSel = e.currentTarget.dataset.status;
      console.log(statusSel)
      my.datePicker({
        format: 'yyyy-MM-dd HH:mm',
        currentDate:  this.farmatDate(new Date(), 'yyyy-MM-dd hh:mm', 7),
        startDate: '2018-01-01 00:00', 
        endDate: this.farmatDate(new Date(), 'yyyy-MM-dd hh:mm', 0),
        success: (res) => {
          console.log(res)
          // 自定义开始时间
          if(statusSel == 1) {
            that.setData({startTime: res.date})
            if(that.data.endTime) {
              that.getTotalData(that.data.startTime)
            }
            // that.getTotalData(that.data.startTime,that.data.endTime)
          // 自定义结束时间
          }else{
            that.setData({endTime: res.date})
            that.getTotalData(that.data.startTime)
          }
        },
      });
    }
  },
  // 自定义结束时间
  datePickerYMDHMS2(e) {
    let that = this;
    if(that.data.selected == 4) {
      console.log(e)
      let statusSel = e.currentTarget.dataset.status;
      console.log(statusSel)
      // let distanceTime = new Date(this.data.startTime);
      // console.log(distanceTime )
      // console.log(new Date())
      // console.log(distanceTime > new Date())
      my.datePicker({
        format: 'yyyy-MM-dd HH:mm',
        currentDate:  that.farmatDate(new Date(this.data.startTime), 'yyyy-MM-dd hh:mm', -7),
        // 开始时间选择的那个时间
        startDate: that.data.startTime, 
        // 结束时间是 开始时间推后7天
        endDate:  that.farmatDate(new Date(this.data.startTime), 'yyyy-MM-dd hh:mm', -7),
        success: (res) => {
          console.log(res)
          // 自定义开始时间
          if(statusSel == 1) {
            that.setData({startTime: res.date})
            if(that.data.endTime) {
              that.getTotalData(that.data.startTime)
            }
            // that.getTotalData(that.data.startTime,that.data.endTime)
          // 自定义结束时间
          }else{
            that.setData({endTime: res.date})
            that.getTotalData(that.data.startTime)
          }
        },
      });
    }
   
  },
  // 按时间段请求数据
  getTotalData(params) {
    console.log('开始',this.data.startTime,'结束',this.data.endTime)
    if(params){
      // 时间段提示先隐藏
      let start = new Date(this.data.startTime);
      let end = new Date(this.data.endTime);
      // console.log(new Date(start) , new Date(end) );
      // console.log(end - start );

      // 如果开始开始大于结束时间
      if( end < start) {
        my.showToast({
          type:'fail',
          content:'开始开始大于结束时间'
        });
        return false
      }
      // 如果选择范围超过7天,重新选择结束时间
      if( (end - start) > 604800000){
        my.showToast({
          type:'fail',
          content:'选择范围超过7天,重新选择结束时间'
        });
        // console.log('选择范围超过7天,重新选择结束时间')
      }else{
        this.getCashierSum({start_time:this.data.startTime,end_time:this.data.endTime})
      }
      // this.getCashierSum({start_time:'2019-10-28 11:11',end_time:'2019-11-01 11:11'})
      console.log('可以请求了')
    }else{
      console.log('开始时间还没选')
      my.showToast({
        type:'fail',
        content:'请选择开始时间',
        success: () => {
          // 清空结束时间
          this.setData({endTime:''})
        }
      });
    }
  },
  // 获取门店列表
  getStoreList() {
    let token = my.getStorageSync({ key: 'token' }).data;
    ajax('/SmallAppDeviceList',{token}).then((res) => {
     console.log(res)
     this.setData({storeList: res.data.list})
    }).catch((err) => {
      console.log(err)
    })
  },
  
  // 获取时间格式2019-11-01 11:11
  farmatDate(old_time, fmt , a) {
    if ( /(y+)/.test(fmt) ){
      fmt = fmt.replace(RegExp.$1, old_time.getFullYear() + '').substr(4 - RegExp.$1.length);
    }
    var time = new Date(old_time);
    time.setDate(old_time.getDate() - a);
    // console.log('ssssss')
    // console.log(time)
    // console.log(fmt)
    let o = {
      'M+': time.getMonth() + 1,
      'd+': time.getDate(),
      'h+': time.getHours(),
      'm+': time.getMinutes(),
      // 's+': getSeconds()
    };
    // console.log(o)
    for (let key in o) {
      let patt1 =new RegExp(`(${key})`);
      if(patt1.test(fmt)){
        let str = o[key] + '';
        fmt = fmt.replace(RegExp.$1, str.length === 2 ? str: this.padLeftZero(str));
      }
    }
    return fmt;
},

// 函数 padLeftZero 的作用：如果月份为1位（如9），则在其左边补0（变为09）
padLeftZero(str) {
  // 原来是这么写的
  // return '0' + str.substr(str.length);
  return '0' + str
},

// fun_date(a){
//     var date1 = new Date(),
//     time1=date1.getFullYear()+"-"+(date1.getMonth()+1)+"-"+date1.getDate();
//     var date2 = new Date(date1);
//         date2.setDate(date1.getDate() + a);
//     var time2 = date2.getFullYear()+"-"+(date2.getMonth()+1)+"-"+date2.getDate();
//       return time2 
//   },

  onLoad() {
    // 获取门店列表
    this.getStoreList();
    // 默认请求该设备的今日账单
    this.getCashierSum({devices:this.data.storeNum,num:0});
  },
  onShow() {
   
  }
});
